<template>
  <page-wrapper>
    <n-card :bordered="false" class="mb-3 proCard">
      <n-space align="center">
        <n-input-group style="width: 380px">
          <n-input
            :style="{ width: '100%' }"
            v-model:value="params.config_name"
            clearable
            placeholder="请输入配置名称"
            @keyup.enter="reloadTable"
          />
          <n-button type="primary" @click="reloadTable">
            <template #icon>
              <n-icon>
                <SearchOutlined />
              </n-icon>
            </template>
            查询
          </n-button>
        </n-input-group>
      </n-space>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-space>
            <n-button type="primary" @click="openCreateDrawer">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              添加配置
            </n-button>
            <n-button @click="openExport">
              <template #icon>
                <n-icon>
                  <ExportOutlined />
                </n-icon>
              </template>
              导出配置
            </n-button>
          </n-space>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :permissionList="treeData"
      @change="reloadTable"
    />
  </page-wrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import type { MessageReactive } from 'naive-ui';
  import { BasicTable, TableAction, BasicColumn } from '@/components/Table';
  import { configList, deleteConfig, exportConfig } from '@/api/system/config';
  import { columns } from './columns';
  import { FileAddOutlined, SearchOutlined, ExportOutlined } from '@vicons/antd';
  import CreateDrawer from './CreateDrawer.vue';
  import { downloadFileBase64 } from '@/utils/index';

  let messageReactive: MessageReactive | null = null;
  const message = useMessage();
  const tableRef = ref();
  const createDrawerRef = ref();
  const drawerTitle = ref('添加配置');
  const treeData = ref([]);
  const exportBtn = ref(false);

  const params = reactive({
    config_name: '',
  });

  const actionColumn: BasicColumn = reactive({
    width: 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            onPositiveClick: handleDelete.bind(null, record),
            isConfirm: true,
            confirmContent: '您确定要删除吗？',
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };
    return await configList(_params);
  };

  function openExport() {
    exportBtn.value = true;
    messageReactive = message.loading('系统正在导出，请稍等');
    exportConfig()
      .then((res) => {
        try {
          if (res.status === 200 && res.data) {
            const response = res.data.data;
            downloadFileBase64(response.file, response.name);
            removeMessage();
            message.success('导出成功');
          }
        } catch {
          removeMessage();
          message.error('系统异常，导出失败');
        }
        exportBtn.value = false;
      })
      .catch(() => {
        exportBtn.value = false;
      });
  }

  function removeMessage() {
    if (messageReactive) {
      messageReactive.destroy();
      messageReactive = null;
    }
  }

  function openCreateDrawer() {
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    tableRef.value.reload();
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    drawerTitle.value = '编辑配置';
    const { openDrawer } = createDrawerRef.value;
    openDrawer(record.id);
  }

  function handleDelete(record: Recordable) {
    deleteConfig({ id: record.id }).then(() => {
      message.success('删除成功');
      reloadTable();
    });
  }

  onMounted(async () => {});
</script>

<style lang="less" scoped></style>
